package com.huazai.rabbitmq.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.listener.RabbitListenerContainerFactory;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * rabbitmq配置类：配置Exchange、Queue、以及绑定交换机
 *
 * @author qzz
 */
@Configuration
public class RabbitDeadConfig {

    private static final Logger log = LoggerFactory.getLogger(RabbitDeadConfig.class);

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Bean
    public RabbitListenerContainerFactory<?> rabbitListenerContainerFactory(ConnectionFactory connectionFactory) {
        //SimpleRabbitListenerContainerFactory发现消息中有content_type有text就会默认将其转换成string类型的
        SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
        factory.setConnectionFactory(connectionFactory);
        /**
         * 比较常用的 Converter 就是 Jackson2JsonMessageConverter,在发送消息时，它会先将自定义的消息类序列化成json格式，
         * 再转成byte构造 Message，在接收消息时，会将接收到的 Message 再反序列化成自定义的类
         */
        factory.setMessageConverter(new Jackson2JsonMessageConverter());
        //开启手动ACK
        factory.setAcknowledgeMode(AcknowledgeMode.MANUAL);
        return factory;
    }

    @Bean
    public AmqpTemplate amqpTemplate() {
        rabbitTemplate.setEncoding("UTF-8");
        rabbitTemplate.setMandatory(true);
        /**
         * ReturnsCallback消息没有正确到达队列时触发回调，如果正确到达队列不执行
         * config : 需要开启rabbitmq发送失败回退
         * yml配置publisher-returns: true
         * 或rabbitTemplate.setMandatory(true);设置为true
         */
        rabbitTemplate.setReturnsCallback(returnedMessage -> {
            String messageId = returnedMessage.getMessage().getMessageProperties().getMessageId();
            byte[] message = returnedMessage.getMessage().getBody();
            Integer replyCode = returnedMessage.getReplyCode();
            String replyText = returnedMessage.getReplyText();
            String exchange = returnedMessage.getExchange();
            String routingKey = returnedMessage.getRoutingKey();

            log.info("============发送失败,消息：{}，消息ID：{} 应答码：{} 原因：{} 交换机：{} 路由键：{}",
                    new String(message), messageId, replyCode, replyText, exchange, routingKey);

        });
        return rabbitTemplate;
    }

    //参考地址 https://www.cnblogs.com/panchanggui/p/13578052.html
    public static final String DELAY_QUEUE = "delay1-queue";
    //出取精室队列队列名称
    public static final String DELAY_EXCHANGE = "delay1-exchange";
    //出取精室的exchange
    public static final String DELAY_ROUTING_KEY = "delay1-routingkey";
    //出取精室routing-key 名称
    public static final String DEAD_QUEUE = "dead1-queue";
    //延时消费的队列名称
    public static final String DEAD_EXCHANGE = "dead1-exchange";
    //延时消费的exchange
    public static final String DEAD_ROUTING_KEY = "dead1-routingkey";
    //延时消费的routing-key名称

    // 创建一个立即消费队列
    @Bean
    public Queue delayQueue() {
        Map<String, Object> params = new HashMap<>();
        // x-dead-letter-exchange 声明了队列里的死信转发到的DLX名称，
        params.put("x-dead-letter-exchange", DEAD_EXCHANGE);
        // x-dead-letter-routing-key 声明了这些死信在转发时携带的 routing-key 名称。
        params.put("x-dead-letter-routing-key", DEAD_ROUTING_KEY);
        return new Queue(DELAY_QUEUE, true, false, false, params);
    }

    // 创建一个延时队列
    @Bean
    public Queue deadQueue() {
        return new Queue(DEAD_QUEUE, true);
    }

    @Bean
    public DirectExchange delayExchange() {
        // 一共有三种构造方法，可以只传exchange的名字， 第二种，可以传exchange名字，是否支持持久化，是否可以自动删除，
        //第三种在第二种参数上可以增加Map，Map中可以存放自定义exchange中的参数
        return new DirectExchange(DELAY_EXCHANGE, true, false);
    }

    @Bean
    public DirectExchange deadExchange() {
        // 一共有三种构造方法，可以只传exchange的名字， 第二种，可以传exchange名字，是否支持持久化，是否可以自动删除，
        // 第三种在第二种参数上可以增加Map，Map中可以存放自定义exchange中的参数
        return new DirectExchange(DEAD_EXCHANGE, true, false);
    }

    //把立即消费的队列和立即消费的exchange绑定在一起
    @Bean
    public Binding delayBinding() {
        return BindingBuilder.bind(delayQueue()).to(delayExchange()).with(DELAY_ROUTING_KEY);
    }

    //把延时消费的队列和延时消费的exchange绑定在一起
    @Bean
    public Binding deadBinding() {
        return BindingBuilder.bind(deadQueue()).to(deadExchange()).with(DEAD_QUEUE);
    }
}

